package com.uniledger.exchange.home;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.rohit.recycleritemclicksupport.RecyclerItemClickSupport;
import com.uniledger.commonlib.lazy.LazyFragmentPagerAdapter;
import com.uniledger.exchange.R;
import com.uniledger.exchange.base.fragment.BaseFragment;
import com.uniledger.exchange.dapp.OnDappListener;
import com.uniledger.exchange.home.scheme.ContactActivity;
import com.uniledger.exchange.home.scheme.PayQRCodeActivity;
import com.uniledger.exchange.home.scheme.UniCaptureActivity;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.StellarAsset;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements
        LazyFragmentPagerAdapter.Laziable,
        EasyPermissions.PermissionCallbacks
        {

    private static final int RC_CAMERA_PERM = 123;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    @BindView(R.id.recycler_home)
    RecyclerView recyclerHome;

    HomeCenterAdapter centerAdapter;

    public static final int REQUEST_SCANNER_CODE = 0X01;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 生成二维码
     */
    public void payClick() {
        Intent intent = new Intent(getActivity(), PayQRCodeActivity.class);
        startActivity(intent);
    }

    /**
     * 扫码
     */
    @AfterPermissionGranted(RC_CAMERA_PERM)
    public void scanClick() {
        if (hasCameraPermission()) {
            scannerCode(UniCaptureActivity.class);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.permissions_camera),
                    RC_CAMERA_PERM,
                    Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    /**
     * 检测是否授予相机权限
     *
     * @return
     */
    private boolean hasCameraPermission() {
        return EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA);
    }

    /**
     * 打开扫码
     */
    private void scannerCode(Class<?> cls) {
        ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeCustomAnimation(getActivity(), R.anim.in, R.anim.out);
        Intent intent = new Intent(getActivity(), cls);
        ActivityCompat.startActivityForResult(getActivity(), intent, REQUEST_SCANNER_CODE, optionsCompat.toBundle());


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SCANNER_CODE && resultCode == Activity.RESULT_OK) {
            //TODO 扫码成功跳转到转账交易页面

            if (data != null) {
                data.setClass(getActivity(), ContactActivity.class);
                startActivity(data);
            }
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());

        centerAdapter = new HomeCenterAdapter(getActivity());

        HorizontalDividerItemDecoration decoration = new HorizontalDividerItemDecoration.Builder(getActivity())
                .color(Color.TRANSPARENT)
                .size(32)
                .showLastDivider()
                .visibilityProvider(centerAdapter)
                .build();

        recyclerHome.addItemDecoration(decoration);
        recyclerHome.setLayoutManager(manager);

//        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int i) {
//                int type = centerAdapter.getItemViewType(i);
//                switch (type) {
//                    case HomeCenter.TYPE_HOME_HEAD:
//                        return 2;
//                    case HomeCenter.TYPE_HOME_ASSET:
//                        return 2;
//                    case HomeCenter.TYPE_HOME_SCHEME:
//                        return 2;
//                    default://分类跳转
//                        return 2;
//                }
//            }
//        });

        recyclerHome.setAdapter(centerAdapter);

        centerAdapter.setHeadListener(new HomeCenterAdapter.HeadListener() {
            @Override
            public void scan() {
                scanClick();
            }

            @Override
            public void pay() {
                payClick();
            }
        });

        RecyclerItemClickSupport.addTo(recyclerHome).setOnItemClickListener(new RecyclerItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                HomeCenter center = centerAdapter.getItemData(position);
                center.click(getActivity());
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //TODO 获取余额信息
        Api.getService().getBalance()
                .compose(RxSchedulers.io_main())
                .subscribe(new Consumer<HttpResult<List<StellarAsset>>>() {
                    @Override
                    public void accept(HttpResult<List<StellarAsset>> httpResult) throws Exception {
                        if (httpResult.data == null || httpResult.data.isEmpty()) {
                            List<StellarAsset> list = new ArrayList<>();
                            list.add(new StellarAsset());
                            centerAdapter.updateAsset(list);
                        } else {
                            centerAdapter.updateAsset(httpResult.data);
                        }
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        List<StellarAsset> list = new ArrayList<>();
                        list.add(new StellarAsset());
                        centerAdapter.updateAsset(list);
                    }
                }));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 请求权限成功
     * 可以弹窗显示结果，也可执行具体需要的逻辑操作
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
//        scannerCode();
    }

    /**
     * 请求权限失败
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        /**
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。
         */
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

}
